<template>
  <t-upload
    ref="uploadRef1"
    :auto-upload="false"
    :action="url"
    :headers="headers"
    theme="image"
    accept="image/*"
    @success="onSuccess"
    @remove="onRemove"
    :default-files="defaultFiles"
    multiple
  />
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { useUserStore } from '@/store';
import { MessagePlugin } from 'tdesign-vue-next';

const props = defineProps<{
  image?: string[] | null;
}>();

const emit = defineEmits(['update:image', 'success']);

const userStore = useUserStore();
const url = import.meta.env.VITE_API_URL_PREFIX + '/common/upload';
const headers = {
  Authorization: 'Bearer ' + userStore.token,
};

// 将传入的 image URL 转换为 t-upload 所需的 default-files 格式
const defaultFiles = computed(() => {
  if (!props.image) return [];
  return props.image.map((urlItem) => ({ url: import.meta.env.VITE_PROXY_API_URL + urlItem }));
});

const uploadRef1 = ref();
const uploadFiles = () => {
  uploadRef1.value.uploadFiles();
};

const onSuccess = (res: any) => {
  const imageUrl = res.response.map((item) => item.fileName);
  emit('update:image', imageUrl);
  emit('success');
  MessagePlugin.success('上传成功');
};

const onRemove = ({ file }: { file: { url: string } }) => {
  if (!props.image) return;

  // 从 URL 中移除代理前缀进行比较
  const proxyUrl = import.meta.env.VITE_PROXY_API_URL;
  const cleanUrl = file.url.startsWith(proxyUrl) ? file.url.slice(proxyUrl.length) : file.url;

  // 过滤掉被删除的图片
  const newImages = props.image.filter((url) => url !== cleanUrl);

  emit('update:image', newImages.length ? newImages : null);
  MessagePlugin.success('图片已删除');
};

defineExpose({
  uploadFiles,
});
</script>
